<?php defined('SYSPATH') or die('No direct script access.');
/*
*
*
*
*/
class Controller_Purchases_Pay extends Controller_Admin{
	public function before()
  {
    try{
      ACL::Required('purchases Pay');
    }catch(HTTP_Exception_403 $e){
			Message::error('sorry，你没有权限进这个目录');
      $this->request->redirect(URL::base(true));
    }
    parent::before();
  }
/**
*采购付款单查询
*/
	public function action_purchasepay()
	{
		$this->title = "新建采购付款单";
		$result = array();
		$view = View::factory('purchase/pay')
				->set('result',$result);
		$this->response->body($view);
	}

	public function action_purchasepaySave()
	{
		$purchase = Config::load('purchase_status');
		$pay_ways  = $purchase->pay_way;
		$this->title = "新建付款单";
		$one_week_before = date('Y-m-d H:i:s',time()-24*3600*7);
		//获取页面传来的参数
		$date_from = isset($_GET['date_from'])?$_GET['date_from']:'';
		$date_to = isset($_GET['date_to'])?$_GET['date_to']:'';
		$purchaseorder_id = isset($_GET['purchaseorder_id'])?$_GET['purchaseorder_id']:'';
		$purchase_id =  isset($_GET['purchase_id'])?$_GET['purchase_id']:'';
		$supplier_name = isset($_GET['supplier_name'])?$_GET['supplier_name']:'';
		if($supplier_name!=''){
//          --------------------------------kdw--------------------------------
//			$sql = "SELECT id from erp_provider WHERE vProviderName = '".$supplier_name."'";
//			$sup = DB::query(Database::SELECT,$sql)->execute('readonlyerp')->as_array();
            $fields=array('id',);
            $conditions=array('name'=>"='". $supplier_name."'",);
            $sup=Newerpclientapi::getSuppliers($fields,$conditions);
//          --------------------------------kdw-end----------------------------
			if(count($sup)!=0){
				$supplier_id = $sup[0]['id'];
				$arr['supplier_id'] = $supplier_id;
			}
		}
		$sql = "SELECT `id` FROM `purchaseorders` WHERE 1 AND status < 100" ;
		if($date_from)
		{
			$sql .= " AND  `purchaseorder_date` >= '".$date_from."' ";
		}
		if($date_to)
		{
			$sql .= " AND  `purchaseorder_date` <= '".$date_to."' ";
		}
		if($purchaseorder_id)
		{
			$sql .= " AND  `id` = '".$purchaseorder_id."' ";
		}
		if($purchase_id)
		{
			$sql .= " AND  `purchase_id` = '".$purchase_id."' ";
		}
		if(!empty($supplier_id))
		{
			$sql .= " AND  `supplier_id` = '".$supplier_id."' ";
		}
		if($_GET['pay_status']!=40)
		{
			$sql = "SELECT * FROM `pay_applicates` WHERE `status`= '".$_GET['pay_status']."' AND purchaseorder_id IN (".$sql.")";
		}
		else
		{
			$sql_cancel = "SELECT distinct(`purchaseorder_id`)  FROM `purchaseorder_details` WHERE `status`=90";
			$sql .= " AND id IN (".$sql_cancel.")";
			$sql  = "SELECT * FROM `pay_applicates` WHERE `status`= '".$_GET['pay_status']."' AND purchaseorder_id IN (".$sql.")";
		}
		$purchasepay_info =DB::query(Database::SELECT,$sql)
											->execute('newerp')
											->as_array();
	    //计算总的查询记录
	  $count = count($purchasepay_info);
	    //分页
	  $pagination         = Pagination::factory(array(
	      'items_per_page'  =>5, 
	      'total_items'     => $count,
	      'uri'	            => $this->request->uri(),
	  ));
		$current_page     = isset($_GET['page'])?$_GET['page']:1;
	  $sql          .= "  LIMIT ".(($current_page-1)*5).",5";
	  $result = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
		
		foreach($result as $key => $value)
		{
			$sql_info = "SELECT `pay_way` 
									FROM `purchaseorders` 
									WHERE `id` =".$value['purchaseorder_id'];
			$pay_way  = DB::query(Database::SELECT,$sql_info)->execute('newerp')->get('pay_way');
			$result[$key]['pay_way'] = $pay_ways[$pay_way];
			
			$sql_info = "SELECT SUM(`amount_paid`) as amount_paid
									FROM `purchase_pays` 
									WHERE `purchaseorder_id` =".$value['purchaseorder_id']." 
									GROUP BY purchaseorder_id";
			$paid     = DB::query(Database::SELECT,$sql_info)->execute('newerp')->current();
			$result[$key]['amount_paid'] = $paid['amount_paid'];
		}
		//$result = DB::query(Database::SELECT,$sql_in)->execute('newerp')->as_array();
		//print_r($result);exit;
		$view = View::factory('purchase/pay')
					->set('pagination',$pagination)
					->set('result',$result);
		$view->set('date_from',$date_from);
		$view->set('date_to',$date_to);
		$view->set('purchaseorder_id',$purchaseorder_id);
		$view->set('purchase_id',$purchase_id);
		$view->set('supplier_name',$supplier_name);
		$view->set('pay_status',$_GET['pay_status']);
		$this->response->body($view);
	}

	public function action_submit_pay()
	{
		$factpay = $_GET['factpay'];
		$remark  = $_GET['remark'];
		$id  		 = $_GET['id'];
		$paid    = $_GET['paid'];
		$ownpay  = $_GET['ownpay'];
		$purchaseorder_id = $_GET['purchaseorder_id'];
		
		$user = User::active_user()->id;
		$sql = "SELECT * FROM `purchaseorders` WHERE id =".$purchaseorder_id ;
		$po  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
		$po['trans_fee'] = $po['money']+$po['transportation_expense'];
		$sql = "INSERT INTO `purchase_pays`(`id`, `purchaseorder_id`,`supplier_id`, `pay_way`, `pay_date`, `payer`, `check_man`, `check_time`, `pay_type`, `amount_payable`, `amount_paid`, `pay_reason`,  `completedornot`, `pay_apply_id`,`transportation_expense`) VALUES ('','".$po['id']."','".$po['supplier_id']."','".$po['pay_way']."','".date('Y-m-d H:i:s',time())."','".User::active_user()->id."','','','','".$po['trans_fee']."','".$factpay."','','0','".$id."','".$po['transportation_expense']."')";
		$ff = DB::query(Database::INSERT,$sql)->execute('newerp');
		if(($paid + $factpay) >= $ownpay)
		{
					$status=30;
		}else{
					$status=20;
		}
		$update = "UPDATE `pay_applicates` SET `status` =".$status." WHERE `purchaseorder_id` =".$purchaseorder_id;
		
		$flag = DB::query(Database::UPDATE,$update)->execute('newerp');
		
		echo json_encode($flag);exit;
	}
	public function action_batch_array_pay()
	{
		$arrChannel = json_decode($_POST['json'],true);
		unset($arrChannel[0]);
		$user = User::active_user()->id;
		foreach($arrChannel as $value)
		{
					$factpay = $value['factpay'];
					$remark  = $value['remark'];
					$id  		 = $value['id'];
					$paid    = $value['paid'];
					$ownpay  = $value['ownpay'];
					$purchaseorder_id = $value['purchaseorder_id'];					
					$sql = "SELECT * FROM `purchaseorders` WHERE id =".$purchaseorder_id ;
					$po  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
					$po['trans_fee'] = $po['money']+$po['transportation_expense'];
					$sql = "INSERT INTO `purchase_pays`(`id`, `purchaseorder_id`,`supplier_id`, `pay_way`, `pay_date`, `payer`, 				`check_man`, `check_time`, `pay_type`, `amount_payable`, `amount_paid`, `pay_reason`,  `completedornot`, `pay_apply_id`,`transportation_expense`) VALUES ('','".$po['id']."','".$po['supplier_id']."','".$po['pay_way']."','".date('Y-m-d H:i:s',time())."','".User::active_user()->id."','','','','".$po['trans_fee']."','".$factpay."','','0','".$id."','".$po['transportation_expense']."')";
					$ff = DB::query(Database::INSERT,$sql)->execute('newerp');
					if(($paid + $factpay) >= $ownpay)
					{
						$status=30;
					}else{
						$status=20;
					}
					$update = "UPDATE `pay_applicates` SET `status` =".$status." WHERE `purchaseorder_id` =".$purchaseorder_id;
		
					$flag = DB::query(Database::UPDATE,$update)->execute('newerp');
		}
		echo json_encode($flag);exit;
	}
	public function action_batch_pay()
	{
		$arrChannel = json_decode($_POST['json'],true);
		unset($arrChannel[0]);
		$user = User::active_user()->id;
		foreach($arrChannel as $value)
		{
					$purchaseorder_id = DB::select('purchaseorder_id')
					->from('purchaseorder_details')
					->where('id','=',$value['detail'])
					->execute('newerp')
					->get('purchaseorder_id');				
					
					$sql = "SELECT * FROM `purchaseorders` WHERE id =".$purchaseorder_id ;
					$po  = DB::query(Database::SELECT,$sql)->execute('newerp')->current();
					$po['trans_fee'] = $po['money']+$po['transportation_expense'];
					$sql = "INSERT INTO `purchase_pays`(`id`, `purchaseorder_id`,`purchase_detail_id`,`sku`,`supplier_id`, `pay_way`, `pay_date`, `payer`, 				`check_man`, `check_time`, `pay_type`, `amount_payable`, `amount_paid`, `pay_reason`,  `completedornot`, `pay_apply_id`,`transportation_expense`) VALUES ('','".$purchaseorder_id."','".$value['detail']."','".$value['sku']."','".$po['supplier_id']."','".$po['pay_way']."','".date('Y-m-d H:i:s',time())."','".User::active_user()->id."','','','','".$po['trans_fee']."','".$value['pay']."','".$value['remark']."','0','','".$po['transportation_expense']."')";
					$ff = DB::query(Database::INSERT,$sql)->execute('newerp');
					if(($value['paid'] + $value['pay']) >= $value['money'])
					{
						$flag = Purchase::judge_status($purchaseorder_id);
						if($flag)
							$status=30;
						else
							$status=20;
					}else{
						$status=20;
					}
					$update = "UPDATE `pay_applicates` SET `status` =".$status." WHERE `purchaseorder_id` =".$purchaseorder_id;
					$flag = DB::query(Database::UPDATE,$update)->execute('newerp');
		}
		echo json_encode($flag);exit;
	}


	public function Action_do_payback()
	{
		$re = false;
		if(isset($_POST['purchaseorder_id'])
			and isset($_POST['purchase_detail_id'])
			and isset($_POST['refund_money'])
			)
		{
			$purchasepay = DB::select()->from('purchase_pays')
			->where('purchaseorder_id','=',trim($_POST['purchaseorder_id']))
			->where('purchase_detail_id','=',trim($_POST['purchase_detail_id']))
			->execute('newerp')
			->as_array();
			
			if(empty($purchasepay))
			{
				echo json_encode($re);exit;
			}
			
			$values = array();
			$values['refund_date'] = date('Y-m-d h:i:s');
			$values['user_id'] = user::active_user()->id?user::active_user()->id:NULL;

			$values['purchaseorder_id'] = $purchasepay[0]['purchaseorder_id'];
			$values['purchase_detail_id'] = $purchasepay[0]['purchase_detail_id'];
			$values['refund_money'] = trim($_POST['refund_money']);

			if(isset($_POST['remark']) and trim($_POST['remark']))
			{
				$values['remark'] = $_POST['remark'];
			}
			
			
			list($insert_id, $total_rows)  = DB::insert('refund_invoices',array_keys($values))
			->values($values)
			->execute('newerp');
			
			if($total_rows>0)
			{
				$re = true;
			}
		}
		echo json_encode($re);exit;
	}
	
		public function Action_purchase_payback()
		{
		$this->title = "采购退款单";

		$condition = array();
		if(isset($_GET['purchase_detail_id']) and trim($_GET['purchase_detail_id']))
		{
			$condition['purchase_detail_id'] = trim($_GET['purchase_detail_id']);
			$purchase_pays = $this->get_purchase_pay($condition);
			
			$purchase_paybacks = $this->get_purchase_payback($condition);
			
		}		
	
		$view = view::factory("purchase/payback");
		$view->set('purchase_pays',$purchase_pays);
		$view->set('purchase_paybacks',$purchase_paybacks);
		$this->response->body($view);
		

	}

	//查询退款记录
	protected function get_purchase_payback(array $condition)
	{
		
		if(empty($condition))
		{
			return;
		}
		$pd_payback_info = DB::select('refund_invoices.*')
		->from('refund_invoices');
		
		//采购单号
		if(isset($condition['purchaseorder_id']) and $condition['purchaseorder_id'])
		{
			$pd_payback_info = $pd_payback_info 
			->where('refund_invoices.purchaseorder_id','=',$condition['purchaseorder_id']);
		}
		
		//采购明细号
		if(isset($condition['purchase_detail_id']) and $condition['purchase_detail_id'])
		{
			$pd_payback_info = $pd_payback_info
			->where('refund_invoices.purchase_detail_id','=',$condition['purchase_detail_id']);
		}
		
		$pd_payback_info = $pd_payback_info ->execute('newerp')->as_array();
		
		if(!$pd_payback_info)
		{
			return ;
		}

		$payback_all=0;
		foreach ($pd_payback_info as $payback)
		{
			$payback_all += $payback['refund_money'];
		}
		
		return array(
				"refund_invoices"=>$pd_payback_info,
				"refund_invoices_all"=>$payback_all);
	}
	
	//查询付款记录
	protected function get_purchase_pay(array $condition)
	{
		// var_dump($condition);exit;
		if(!$condition)
		{
			return;
		}
		$pd_pay_info = DB::select('purchase_pays.*')
			->from('purchase_pays');

		if(isset($condition['purchaseorder_id']))
		{
			$pd_pay_info = $pd_pay_info
			->where('purchase_pays.purchaseorder_id','=',$condition['purchaseorder_id']);
		}
		
		//采购详情号
		if(isset($condition['purchase_detail_id']))
		{
			$pd_pay_info = $pd_pay_info
			->where('purchase_pays.purchase_detail_id','=',$condition['purchase_detail_id']);
		}
		
		$pd_pay_info = $pd_pay_info
						->execute('newerp')
						->as_array();
		//var_dump($pd_pay_info);exit;
		if(!$pd_pay_info)
		{
			return ;
		}
		//付款总额
		if($pd_pay_info)
		{
			$pay_all = 0;
			foreach ($pd_pay_info as $pay)
			{
				$pay_all += $pay['amount_paid'];
			}
			
		}
		return array('purchase_pays'=>$pd_pay_info,
					'purchase_pays_all'=>$pay_all);
	}
}
